package com.heima.comment.interceptor;

import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.thread.ApThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

@Slf4j
public class ApTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.获取token请求头
        String token = request.getHeader("token");
        // 2.校验token
        Optional<String> optional = Optional.ofNullable(token);
        // 如果token不存在，拦截
        if (!optional.isPresent()) {
            return false;
        }
        // 3.获取token中的载荷，并提取用户信息
        Integer userId = (Integer) AppJwtUtil.getClaimsBody(token).get("id");
        // 4.保存用户信息
        ApUser apUser = new ApUser();
        apUser.setId(userId);
        ApThreadLocalUtil.setUser(apUser);
        // 5.放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("清理threadlocal...");
        ApThreadLocalUtil.removeUser();
    }
}
